#include <iostream>
#include "TcpServer.hpp"
#include "Socket.hpp"
#include "protocol.hpp"
#include <memory>
#include <string>
#include <unistd.h>
#include <ctime>
#include <cstdlib>
static const std::string &opers = "+-*/%";

int main(int argc, char *argv[])
{
    srand(time(nullptr));
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << "serverip serverport" << std::endl;
        exit(-1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    SockpPtr sock = std::make_shared<Tcp_socket>();
    if (!sock->BuidClientSocket(serverip, serverport))
    {
        std::cerr << "link error!" << std::endl;
        exit(1);
    }
    std::string Pacagestream;
    while (true)
    {
        
        // 构建请求
        auto request = Factor::BuildRequestDefault();
        //自定义请求
        int x = rand() % 10+1;
        int y = rand() % 10+1;
        char oper = opers[getpid() % opers.size()];
        request->SetValue(x,oper,y);
        std::string reqstr;
        request->Serialization(&reqstr);

        std::cout<<reqstr<<std::endl;
        // 添加报文
        std::string clientJson = Encode(reqstr);
        sock->Send(clientJson);
        auto res = Factor::BuildRespenceDefault();
        // 接收请求
        while (true)
        {
            ssize_t n = sock->Recv(&Pacagestream);
            if (n <= 0)
                break;
            std::string package = Decode(Pacagestream);
            if (package.empty())
                continue;
            res->Deserialization(package);
            res->print();
            break;
        }
        sleep(1);
    }
    sock->Close();
    return 0;
}